import { ChromeOutlined } from "@ant-design/icons";
import { Button, Popover, Spin } from "antd";
import { useEffect, useRef, useState } from "react";
import { useIframeMessage } from "@/hooks/useIframe";
import styles from "./index.less";

interface VeloceProps {
  onUpdate?: (data: any, isComplete?: boolean) => void;
  onChange?: (data: any, isComplete?: boolean) => void;
}

const Veloce = (props: VeloceProps) => {
  const { onUpdate, onChange } = props;
  const Domain = "http://localhost:6789";
  const iframeUrl = `${Domain}/ScreenChat`;
  const iframeRef = useRef<any>(null);
  const [isIframeLoading, setIsIframeLoading] = useState(true);
  const iframePageLoad = () => {
    setIsIframeLoading(false);
  };
  // 处理接收到的消息
  const handleIframeMessage = (data: IframeMessageType, event: MessageEvent) => {
    const type = data.type;
    const messageData = data.payload?.messageData;
    const isComplete = data.payload?.isComplete;
    if (type === "update") {
      onUpdate?.(messageData, isComplete);
    }
    if (type === "success") {
      onChange?.(messageData, isComplete);
    }
  };

  const { loading, sendMessage } = useIframeMessage(iframeRef, Domain, handleIframeMessage);

  useEffect(() => {
    const iframe = iframeRef.current;
    iframe?.addEventListener("load", iframePageLoad);

    return () => {
      if (iframeRef.current) {
        iframeRef.current.src = "";
      }
      iframe?.removeEventListener("load", iframePageLoad);
    };
  }, []);

  return (
    <div className={styles.veloceCmp}>
      <Popover
        placement="leftTop"
        trigger={["click"]}
        fresh
        arrow={false}
        classNames={{
          body: styles.popoverContent,
        }}
        content={
          <iframe ref={iframeRef} className={styles.iframe} src={iframeUrl} allow="clipboard-read; clipboard-write" />
        }
      >
        <Button shape="circle" icon={<ChromeOutlined />} />
      </Popover>
    </div>
  );
};

export default Veloce;
